const { appId, appsecret } = require('../uteil')
const axios = require('axios')
const fs = require('fs')
module.exports = {

    //请求access
    getAccessToken() {
        return new Promise((resolve, reject) => {
            axios.get(`https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appId}&secret=${appsecret}`).then(res => {
                // console.log('请求到sccesstoken');
                
                this.saveAccessToken(res.data)
                resolve()
            }).catch(err=>{
            	console.log('accessToken请求错误',err)
            })
        })
    },

    //判断是否过期
     isValueAccessToken(expires_in) {
     	// console.log('文件的：'+Date(expires_in),'当前时间戳：'+Date(Date.now()))
        return expires_in > Date.now()
    },

    //保存access
    saveAccessToken(data) {

        //当前时间加2小时后 -5分钟
        data.expires_in = Date.now() + (data.expires_in - 300) * 1000

        fs.writeFile(__dirname + '/../data/accessToken.txt', JSON.stringify(data), (err) => {
            if (err) {
                console.log('accessToken写入错误', err);

            } else {
                // console.log('accessToken写入成功');

            }
        })
    },

    //读取access
    readAccessToken() {
        return new Promise((resolve, reject) => {

            fs.readFile(__dirname + '/../data/accessToken.txt', (err, data) => {

                if (!err) {
                    // console.log('accessToken文件读取成功');
                    if (data.length > 0) {
                        resolve(JSON.parse(data))
                    } else {
                        console.log('accessToken文件为空');
                        reject()
                    }
                } else {
                    console.log('accessToken文件读取失败', err);
                    reject()
                }
            })
        })
    },

    //拿到一个可用的access
    fetchAccessToken() {
        return new Promise((resolve, reject) => {

            //从本地读取
            this.readAccessToken()
                .then(async res => {
                    //如果没有过期则返回
                    // console.log(res)
                    if (this.isValueAccessToken(res.expires_in)) {
                    	// console.log('access没有过期')
                        resolve(res)
                    } else {
						console.log('access已过期')
                        //如果过期了则重新请求后返回
                        await this.getAccessToken()
                        let result = await this.readAccessToken()
                        resolve(result)
                    }
                })
                .catch(async err => {
                    //如果读取失败了则重新请求后返回
                    await this.getAccessToken()
                    let result = await this.readAccessToken()
                    resolve(result)
                })
        })
    }
}